//
//  StatuesPictureView.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/6/2.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

let XMGPictureViewCellReuseIdentifier = "XMGPictureViewCellReuseIdentifier"
class StatuesPictureView: UICollectionView {

    /// 数据模型
    var modle:Status? {
        didSet {
            //刷新表格
            reloadData()
        }
    }
    /// 布局对象
    private var picturelayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    init() {
        super.init(frame: CGRect.zero, collectionViewLayout: picturelayout)
        translatesAutoresizingMaskIntoConstraints = false
        //1.注册cell
        register(pictureCollectionViewCell.self, forCellWithReuseIdentifier: XMGPictureViewCellReuseIdentifier)
        
        //设置相关的数据源
        dataSource = self
        delegate = self
        
        //设置cell的间隙
        picturelayout.minimumLineSpacing = 10
        picturelayout.minimumInteritemSpacing = 10
        
        //设置配图的背景色
        backgroundColor = UIColor.clear

    }
    
    /// 计算配图的尺寸
    ///
    /// - Returns: 返回collectionView的size 和 item的Size
    func calculateImageSize() -> CGSize {//函数返回的类型是个元组
        
        /// 获取图片的数量
        let pictureCount = modle?.pic_urls?.count
        //1.判断有没有图片
        if pictureCount == 0 || pictureCount == nil {
            return CGSize.zero
        }
        //2.判断只有一张图片则显示把图片的实际尺寸
        if pictureCount == 1 {
            //2.1取出缓存的图片
            let key = modle?.cachesImageURLS?.first?.absoluteString
            //print("key=======",key)
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: key)
            
            //设置Item的大小
            picturelayout.itemSize = image!.size
            //2.2返回缓存图片的实际大小
            return (image?.size)!
        }
        //3.判断图片是不是有4张图片  计算田字格的大小
        let width = 90  //item的大小
        let margin = 10 //item之间的间距
        if pictureCount == 4 {
            let viewWidth = width * 2 + margin //整个田字格的大小
            //设置item的带下
            picturelayout.itemSize = CGSize(width: width, height: width)
            
            return CGSize(width: viewWidth, height: viewWidth)
        }
        //4.如果是其他(多张 ) 计算九宫格的大小
        //2.3.5.6.7.8.9  这些数量的照片
        //4.1 计算九空格的列数
        let colNumber = 3
        //4.2计算行数
        let rowNumber = (pictureCount! - 1)/3 + 1
        //4.3计算collectionView的宽度
        let viewWidth = colNumber * width + (colNumber - 1) * margin
        //4.4 计算collectionView的高度
        let viewHeight = rowNumber * width + (rowNumber - 1) * margin
        
        //设置item的带下
        picturelayout.itemSize = CGSize(width: width, height: width)
        
        return CGSize(width: viewWidth, height: viewHeight)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}


extension StatuesPictureView :UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return modle?.cachesImageURLS?.count ?? 0;
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: XMGPictureViewCellReuseIdentifier, for: indexPath) as! pictureCollectionViewCell
        
        cell.iconImageURL = modle?.cachesImageURLS?[indexPath.row] as URL?
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //print(modle?.cachesLargeImageURLS?[indexPath.item])
        //要发送一个通知, 把当前图片index 和 图片数组 传递给tableView  然后在传递给展示控制器
        //如果是 只包含一层 就是用delegate(代理传值)   如果是多层 使用通知传值
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: pictureCollectionViewCellSelected), object: self, userInfo: [pictureCollectionViewCellIndexkey: indexPath.item,pictureCollectionViewCellURLSkey: modle!.cachesLargeImageURLS!])
    }
}
/// 自定义collectionViewCell
private class pictureCollectionViewCell: UICollectionViewCell {
    
    var iconImageURL: URL? {
        didSet {
            //print(iconImageURL!)
            //1.给图片赋值
            iconImageView.sd_setImage(with: iconImageURL!)
            
            //2.判断是不是gif图
            let urlString = iconImageURL!.absoluteString.lowercased() //as NSString
            if urlString.hasSuffix("gif") {
                gifImageView.isHidden = false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加子控件
        contentView.addSubview(iconImageView)
        iconImageView.addSubview(gifImageView);
        gifImageView.isHidden = true
        
        //布局子控件
        contentView.addConstraint(NSLayoutConstraint.init(item: iconImageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 1))
        contentView.addConstraint(NSLayoutConstraint.init(item: iconImageView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint.init(item: iconImageView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.width, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint.init(item: iconImageView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: contentView, attribute: NSLayoutAttribute.height, multiplier: 1.0, constant: 0))
        
        iconImageView.addConstraint(NSLayoutConstraint.init(item: gifImageView, attribute: .right, relatedBy: .equal, toItem: iconImageView, attribute: .right, multiplier: 1.0, constant: 0))
        iconImageView.addConstraint(NSLayoutConstraint.init(item: gifImageView, attribute: NSLayoutAttribute.bottom, relatedBy: .equal, toItem: iconImageView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0))
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 懒加载ImageView
    private lazy var iconImageView = UIImageView.creatUIImageView(placeholderImage: "")
    
    /// gif图标
    private lazy var gifImageView = UIImageView.creatUIImageView(placeholderImage: "avatar_grassroot")
}

/// 选中图片的通知名称
let pictureCollectionViewCellSelected = "pictureCollectionViewCellSelected"

/// 选中当前图片的下标(index) key
let pictureCollectionViewCellIndexkey = "pictureCollectionViewCellIndexkey"

/// 选中图片的图片数组的key
let pictureCollectionViewCellURLSkey = "pictureCollectionViewCellURLSkey"

